import React, { useState, useEffect } from 'react'
import { BrowserRouter as Router, Routes, Route, Navigate } from 'react-router-dom'
import Sidebar from './components/Sidebar'
import Dashboard from './pages/Dashboard'
import GatewayConfig from './pages/GatewayConfig'
import UserManagement from './pages/UserManagement'
import MenuManagement from './pages/MenuManagement'
import RouteManagement from './pages/RouteManagement'
import Login from './pages/Login'
import { Home, Settings, Users, Menu, Route as RouteIcon, LogOut } from 'lucide-react'

// 路由保护组件
function ProtectedRoute({ children }) {
  const isAuthenticated = localStorage.getItem('isAuthenticated') === 'true'
  return isAuthenticated ? children : <Navigate to="/login" replace />
}

function App() {
  const [sidebarOpen, setSidebarOpen] = useState(true)
  const [isAuthenticated, setIsAuthenticated] = useState(false)
  const [currentUser, setCurrentUser] = useState(null)

  useEffect(() => {
    // 检查登录状态
    const checkAuthStatus = () => {
      const authStatus = localStorage.getItem('isAuthenticated') === 'true'
      const userData = localStorage.getItem('currentUser')
      
      setIsAuthenticated(authStatus)
      if (userData) {
        setCurrentUser(JSON.parse(userData))
      }
    }

    // 初始检查
    checkAuthStatus()

    // 监听storage变化（用于登录/登出）
    const handleStorageChange = () => {
      checkAuthStatus()
    }

    // 添加事件监听器
    window.addEventListener('storage', handleStorageChange)
    
    // 定期检查（每500ms检查一次，用于处理同页面的登录）
    const interval = setInterval(checkAuthStatus, 500)

    return () => {
      window.removeEventListener('storage', handleStorageChange)
      clearInterval(interval)
    }
  }, [])

  const navigation = [
    { name: '仪表盘', href: '/', icon: Home },
    { name: '网关配置', href: '/gateway', icon: Settings },
    { name: '路由管理', href: '/routes', icon: RouteIcon },
    { name: '用户管理', href: '/users', icon: Users },
    { name: '菜单管理', href: '/menus', icon: Menu }
  ]

  const handleLogout = () => {
    localStorage.removeItem('isAuthenticated')
    localStorage.removeItem('currentUser')
    setIsAuthenticated(false)
    setCurrentUser(null)
  }

  if (!isAuthenticated) {
    return (
      <Router>
        <Routes>
          <Route path="/login" element={<Login />} />
          <Route path="*" element={<Navigate to="/login" replace />} />
        </Routes>
      </Router>
    )
  }

  return (
    <Router>
      <div className="min-h-screen flex bg-gray-900">
        <Sidebar 
          navigation={navigation}
          open={sidebarOpen} 
          onToggle={() => setSidebarOpen(!sidebarOpen)}
          currentUser={currentUser}
          onLogout={handleLogout}
        />
        
        <div className={`flex-1 transition-all duration-300 ${sidebarOpen ? 'ml-64' : 'ml-0'}`}>
          <div className="p-6">
            <Routes>
              <Route path="/" element={
                <ProtectedRoute>
                  <Dashboard />
                </ProtectedRoute>
              } />
              <Route path="/gateway" element={
                <ProtectedRoute>
                  <GatewayConfig />
                </ProtectedRoute>
              } />
              <Route path="/routes" element={
                <ProtectedRoute>
                  <RouteManagement />
                </ProtectedRoute>
              } />
              <Route path="/users" element={
                <ProtectedRoute>
                  <UserManagement />
                </ProtectedRoute>
              } />
              <Route path="/menus" element={
                <ProtectedRoute>
                  <MenuManagement />
                </ProtectedRoute>
              } />
              <Route path="/login" element={<Navigate to="/" replace />} />
              <Route path="*" element={<Navigate to="/" replace />} />
            </Routes>
          </div>
        </div>
      </div>
    </Router>
  )
}

export default App